package com.xuecheng.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.basic.domain.Category;
import com.xuecheng.basic.mappers.CategoryMapper;
import com.xuecheng.basic.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.utils.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author 七安
 * @since 2022-09-19
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 查询课程分类目录
     * @return 分类结果
     */
    @Override
    public CategoryVo findCourseType() {
        //查询根节点
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //根节点的ParentId为0
        wrapper.eq(Category::getParentid, "0");
        Category category = categoryMapper.selectOne(wrapper);
        //将category对象转为Vo对象
        CategoryVo categoryVo = BeanHelper.copyProperties(category, CategoryVo.class);
        //调用下面的方法查询(二级分类）
        List<CategoryVo> sonCourseType = findSonCourseType(categoryVo.getId());
        //将二级分类放入根节点中
        categoryVo.setCategoryTreeNodes(sonCourseType);
        //查询(三级分类)
        for (CategoryVo vo : sonCourseType) {
            List<CategoryVo> threeCourseTpye = findSonCourseType(vo.getId());
            //将三级分类放入vo对象中
            vo.setCategoryTreeNodes(threeCourseTpye);
        }
        //返回根节点对象
        return categoryVo;
    }

    /**
     * 查询子课程分类的方法
     *
     * @param id 父节点的id
     * @return 结果集
     */
    public List<CategoryVo> findSonCourseType(String id) {
        //创建Wrapper对象
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getParentid, id);
        List<Category> categoryList = categoryMapper.selectList(wrapper);
        return BeanHelper.copyWithCollection(categoryList, CategoryVo.class);
    }
}
